//
//  MyLayout.m
//  15-UI-Wangyi
//
//  Created by Snow on 16/8/3.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "MyLayout.h"

@interface MyLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributeArray;
@property (nonatomic, assign) NSInteger line;
@property (nonatomic, assign) CGFloat contentWidth;
@end
@implementation MyLayout
- (instancetype) init
{
    self = [super init];
    if (self) {
        _attributeArray = [NSMutableArray array];
        _contentWidth = 0.0f;
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _attributeArray = [NSMutableArray array];
        _contentWidth = 0.0f;
    }
    return self;

}
- (void)prepareLayout
{
    //清空内容宽度
    self.contentWidth = 0.0f;
    //清空layoutAttribute数组
    if (_attributeArray.count != 0) {
        [_attributeArray removeAllObjects];
    }
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        CGFloat y = 0;
        CGFloat height = 40;
        CGFloat width = [self.delegate collectionView:self.collectionView layout:self height:40 heightForItemAtIndexPath:index];
        CGFloat x = _contentWidth;
        attribute.frame = CGRectMake(x, y, width + 10, height);
        _contentWidth = _contentWidth + width + 10;
        [_attributeArray addObject:attribute];
    }
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _attributeArray;
}
- (CGSize)collectionViewContentSize
{
    return CGSizeMake(_contentWidth, 0);
}
@end
